// pages/admin/pet-manage/pet-manage.js
const { get, del } = require('../../../utils/request')
const { getImageUrl, formatDate, showSuccess, showError, showConfirm, debounce } = require('../../../utils/util')

Page({
  data: {
    petList: [],
    searchName: '',
    typeIndex: 0,
    statusIndex: 0,
    typeList: ['全部类型', '猫', '狗', '其他'],
    statusList: ['全部状态', '待领养', '已领养'],
    loading: false
  },

  onLoad() {
    // 检查管理员权限
    const app = getApp()
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'ADMIN') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.loadPetList()
  },

  onShow() {
    this.loadPetList()
  },

  onPullDownRefresh() {
    this.loadPetList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载宠物列表
  loadPetList(callback) {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {}

    // 添加搜索条件
    if (this.data.searchName) {
      params.name = this.data.searchName
    }

    // 添加类型筛选
    if (this.data.typeIndex > 0) {
      params.type = this.data.typeList[this.data.typeIndex]
    }

    // 添加状态筛选
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex]
    }

    get('/pet/list', params).then(res => {
      const petList = res.data || []
      
      // 处理数据
      petList.forEach(item => {
        // 处理图片
        if (item.images) {
          const images = item.images.split(',')
          item.imageUrl = getImageUrl(images[0]) || '/images/default-pet.png'
        } else {
          item.imageUrl = '/images/default-pet.png'
        }
        
        // 格式化时间
        item.createTime = formatDate(item.createTime)
      })

      this.setData({
        petList
      })
    }).catch(err => {
      showError('加载失败')
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 搜索输入
  onSearchInput: debounce(function(e) {
    this.setData({
      searchName: e.detail.value
    })
  }, 300),

  // 搜索
  onSearch() {
    this.loadPetList()
  },

  // 类型筛选
  onTypeChange(e) {
    this.setData({
      typeIndex: parseInt(e.detail.value)
    })
    this.loadPetList()
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value)
    })
    this.loadPetList()
  },

  // 重置筛选
  onReset() {
    this.setData({
      searchName: '',
      typeIndex: 0,
      statusIndex: 0
    })
    this.loadPetList()
  },

  // 添加宠物
  addPet() {
    wx.navigateTo({
      url: '/pages/admin/pet-form/pet-form'
    })
  },

  // 编辑宠物
  editPet(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/admin/pet-form/pet-form?id=${id}`
    })
  },

  // 删除宠物
  async deletePet(e) {
    const { id, name } = e.currentTarget.dataset
    
    try {
      await showConfirm(`确定要删除宠物"${name}"吗？此操作不可恢复。`)
    } catch {
      return
    }

    del(`/pet/${id}`).then(res => {
      showSuccess('删除成功')
      this.loadPetList()
    }).catch(err => {
      showError(err.msg || '删除失败')
    })
  }
})
